/*
 * THIS FILE IS PART OF Zhejiang LiShi Technology CO.,LTD.
 * Copyright (c) 2019-2023  Zhejiang LiShi Technology CO.,LTD.
 * It is forbidden to distribute or copy the code under this software without the consent of the Zhejiang LiShi Technology
 *
 *     https://www.lishiots.com/
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */


package com.example.demo.listener;

import com.example.demo.controller.user.UserController;
import com.example.demo.service.user.impl.UserServiceImpl;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.Generated;
import lombok.SneakyThrows;
import okhttp3.Response;
import okhttp3.ResponseBody;
import okhttp3.sse.EventSource;
import okhttp3.sse.EventSourceListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Objects;
import java.util.concurrent.CountDownLatch;

/**
 * 描述： sse event listener
 */
public class ConsoleEventSourceListener extends EventSourceListener {
    final CountDownLatch countDownLatch;
    private static UserController userController=new UserController();
    @Generated
    private static final Logger log = LoggerFactory.getLogger(ConsoleEventSourceListener.class);
    @Generated
    public ConsoleEventSourceListener(final CountDownLatch countDownLatch) {
        this.countDownLatch = countDownLatch;
    }
    @Override
    public void onOpen(EventSource eventSource, Response response) {
//        log.info("LLM建立sse连接...");
    }
    
    @Override
    public void onEvent(EventSource eventSource, String id, String type, String data) {
//        log.info("LLM返回,id:{},type:{},数据：{}", id, type, data);
//        System.out.print(data);
        ObjectMapper objectMapper = new ObjectMapper();
        JsonNode jsonNode = null;
        try {
            jsonNode = objectMapper.readTree(data);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
        String event = jsonNode.get("event").asText();
        if (event.equals("workflow_finished")){
            userController.stopStream();
        }
        if (jsonNode.has("data") && jsonNode.get("data").has("text")) {
            String text = jsonNode.get("data").get("text").asText();
            System.out.print(text);
            userController.sendToClients(text);
//            System.out.print();
//            JsonNode outputs = jsonNode.get("data").get("text");
//            if (outputs.has("result")) {
//                String result = outputs.get("result").asText();
//                if (!builder.toString().contains(result)) {
//                    builder.append(result);
//                    System.out.print(result);
//                }
////                if (data.contains("\n")) {
////                    System.out.println("换行了");
////                }
//
//            }
        }
    }
    
    @Override
    public void onClosed(EventSource eventSource) {
//        log.info("LLM关闭sse连接...");
        countDownLatch.countDown();
    }
    
    @SneakyThrows
    @Override
    public void onFailure( EventSource eventSource, Throwable t, Response response) {
        try {
            this.countDownLatch.countDown();
            if (Objects.isNull(response)) {
                log.error("LLM  sse连接异常", t);
                eventSource.cancel();
            } else {
                ResponseBody body = response.body();
                if (Objects.nonNull(body)) {
                    log.error("error1-----------------");
                    log.error("LLM  sse连接异常data：{}", body.string(), t);
                } else {
                    log.error("error2-----------------");
                    log.error("LLM  sse连接异常data：{}", response, t);
                }

                eventSource.cancel();
            }
        } catch (Throwable var5) {
            Throwable e= var5;
        }
    }
}
